//
//  NearMenViewController.m
//  安好
//
//  Created by 马晓良 on 14-12-12.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "NearMenViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "NearFirendTableCell.h"
#import "MyFirendData.h"
#import "FirendDetailViewController.h"
@interface NearMenViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate>
{
    CLLocationCoordinate2D tolocation;
}
/**
 *  显示数据
 */
@property (strong, nonatomic) IBOutlet UITableView *nearMenTableView;
@property (nonatomic, strong) CLLocationManager *locationger;
// 经纬度
@property (nonatomic, strong) NSString *latitude;
@property (nonatomic, strong) NSString *longitude;
@property (nonatomic, strong) NSMutableArray *nearFirendArr;
@end

@implementation NearMenViewController

- (NSMutableArray *)nearFirendArr{
    if (_nearFirendArr == nil) {
        self.nearFirendArr = [NSMutableArray array];
    }
    return _nearFirendArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nearMenTableView.dataSource = self;
    self.nearMenTableView.delegate = self;
    self.nearMenTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self creatlocation];
    [self setNaviBarAttribute];
    // Do any additional setup after loading the view from its nib.
}


#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationItem.title = @"附近的人";
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableView的代理方法 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.nearFirendArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 64;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NearFirendTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"firendCell"];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NearFirendTableCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NearFirendTableCell" owner:self options:nil] firstObject];
        }
    }
    MyFirendData *objc = [self.nearFirendArr objectAtIndex:indexPath.row];
    
    cell.nearName.frame = CGRectMake(77, 12, 8, 18);
    cell.nearName.text = objc.username;
    cell.nearName.numberOfLines = 1;
    CGSize size = CGSizeMake(300, 18);
    //获取当前文本的属性
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:TITLE_TEXTLABEL_FOUNT_SIZE],NSFontAttributeName,nil];
    CGSize redSize = [objc.username boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    cell.nearName.frame = CGRectMake(74, 8, redSize.width + 10, 18);
    cell.nearFirendSexImage.frame = CGRectMake(74 + redSize.width + 15, 8, 16, 16);
    
    if ([objc.gender intValue] == 1){
        cell.nearFirendSexImage.image = [UIImage imageNamed:@"men"];
    }else if([objc.gender intValue] == 2){
        cell.nearFirendSexImage.image=[UIImage imageNamed:@"women"];
    }else{
        cell.nearFirendSexImage.hidden = YES;
    }

    cell.headerPicImage.layer.masksToBounds = YES;
    cell.headerPicImage.layer.cornerRadius = 2;
    [cell.headerPicImage  setImageWithURL:[NSURL URLWithString:objc.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
//    cell.nearName.text = objc.username;
    cell.introduceLable.text = objc.bio;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyFirendData *objc = [self.nearFirendArr objectAtIndex:indexPath.row];
    FirendDetailViewController *firendDetailVC = [[FirendDetailViewController alloc] init];
    firendDetailVC.firendId = objc.uid;
    [self.navigationController pushViewController:firendDetailVC animated:YES];
}

- (void)creatlocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationger = [[CLLocationManager alloc] init];
        self.locationger.distanceFilter = 1000;
        self.locationger.delegate=self;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
        
        if (IOS8_OR_LATER) {
            [self.locationger requestAlwaysAuthorization];
        }
#endif
        [self.locationger startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        casekCLAuthorizationStatusNotDetermined:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
            if ([self.locationger respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationger requestAlwaysAuthorization];
            }
#endif
            break;
        default:
            break;
    }
}

//定位
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    manager.delegate=nil;
    [self.locationger stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLLocationCoordinate2D coor = currentLocation.coordinate;
    self.latitude = [NSString stringWithFormat:@"%f",coor.latitude] ;
    self.longitude = [NSString stringWithFormat:@"%f",coor.longitude];
    [self postUserLatAndLongtude];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
   [self showCustomHudSingleLine:@"请先打开GPS"];
}

/**
 *  上传用户经纬度
 */
- (void)postUserLatAndLongtude
{
    NSString * postURL = [NSString stringWithFormat:@"%@user/lnglat/",kBaseURL];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    UserModel * userModel = [[UserManager shareInstance]getUserInfo];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:kPlatform forKey:@"platform"];
    [dic setValue:kVersion forKey:@"version"];
    [dic setValue:self.latitude forKey:@"lat"];
    [dic setValue:self.longitude forKey:@"lng"];
    [dic setValue:[userdefault valueForKey:[NSString stringWithFormat:@"%@gender",userModel.uid]] forKey:@"gender"];
    [dic setValue:@"1" forKey:@"status"];
    [manage POST:postURL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            [self loadDataWithType];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
- (void)loadDataWithType
{
    CLAuthorizationStatus status=[CLLocationManager authorizationStatus];
    if (status==kCLAuthorizationStatusDenied||kCLAuthorizationStatusRestricted==status) {
        [self showCustomHudSingleLine:@"你必须允许“安好”来确定你的位置."];
        return;
    }
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/near/",kBaseURL];
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"lat":self.latitude,
                                 @"lng":self.longitude,
                                 @"type":@"1",
                                 //可见？
                                 @"status":@"1",
                                 };
    [manage POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
        }else{
            NSArray *jsonDictArr = [[responseObject objectForKey:@"data"] isEqual:[NSNull null]]?nil:[responseObject objectForKey:@"data"];
            MyNSLog("%@",jsonDictArr);
            if (jsonDictArr != nil) {
                for (NSDictionary * dic in jsonDictArr){
                    MyFirendData *data = [[MyFirendData alloc] init];
                    [data setValuesForKeysWithDictionary:dic];
                    [self.nearFirendArr addObject:data];
                }
                [self.nearMenTableView reloadData];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
